package menu

import (
	"context"
	"github.com/pkg/errors"
	"trusteva/app/rbac/model"

	"trusteva/app/rbac/internal/svc"
	"trusteva/app/rbac/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MenuAddActionsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMenuAddActionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MenuAddActionsLogic {
	return &MenuAddActionsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MenuAddActionsLogic) MenuAddActions(req *types.MenuAddActionsRo) (resp *types.BaseRsp, err error) {
	var menu model.MenuConfig
	if err = l.svcCtx.DB.WithContext(l.ctx).Where("Id=?", req.MenuId).First(&menu).Error; err != nil {
		return nil, errors.Wrap(err, "菜单不存在")
	}

	for _, v := range req.Actions {
		var action model.ActionConfig
		if err = l.svcCtx.DB.WithContext(l.ctx).Where("Id=?", v).First(&action).Error; err != nil {
			return nil, errors.Wrap(err, "功能不存在")
		}
		menu.Actions = menu.Actions.Add(v)
	}

	err = l.svcCtx.DB.WithContext(l.ctx).Model(&model.MenuConfig{}).Where("Id=?", req.MenuId).
		Update("Actions", menu.Actions).Error

	return
}
